package han.study.preparedstatement.blob;

import han.study.bean.Customer;
import han.study.utils.JDBCUtils;
import org.junit.Test;

import java.io.*;
import java.sql.*;

public class BlobTest {
    // 插入Blob数据
    @Test
    public void testInsert() throws Exception{
        Connection conn = JDBCUtils.getConnection();
        String sql = "insert into customers (name,email,birth,photo) values (?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,"张宇");
        ps.setObject(2,"zhangyu@qq.com");
        ps.setObject(3,"1992-08-28");
        FileInputStream is = new FileInputStream(new File("linyuner.jpg"));
        ps.setBlob(4, is);
        ps.execute();
        JDBCUtils.closeResource(conn,ps);
    }
    // 查看Blob数据
    @Test
    public void testQuery(){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try{
            conn = JDBCUtils.getConnection();
            String sql = "select * from customers where id=?";
            ps = conn.prepareStatement(sql);
            ps.setObject(1,19);
            rs = ps.executeQuery();
            if(rs.next()){
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String email = rs.getString(3);
                Date birth = rs.getDate(4);
                Customer customer = new Customer(id,name,email,birth);
                System.out.println(customer);
                // 获取二进制照片
                Blob photo = rs.getBlob(5);
                is = photo.getBinaryStream();
                fos = new FileOutputStream("zhangyu.jpg");
                byte[] buffer = new byte[1024];
                int len;
                while((len=is.read(buffer)) != -1){
                    fos.write(buffer,0,len);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(is != null) is.close();

            }catch (Exception e){
                e.printStackTrace();
            }

            try {
                if(fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JDBCUtils.closeResource(conn,ps,rs);
        }

    }
}
